ko.validation.rules['changeLimit'] = {
	validator : function(val, options) {
		return Math.abs(val - options.baseValueAccessor()) <= options.maxChange;
	},
	message : 'Change limit exeeded'
};

/**
 * BO Tab3 ViewModel
 */
var tab3RootSelf;
var getMyDateFromStr = function(theDate) {
	var strArr1 = theDate.split("-");
	// years, months, date
	var theDate = new Date(strArr1[0], Number(strArr1[1] - 1), strArr1[2]);
	return theDate;
};
var getMyDate = function(theDate) {
	var myDate = new Date(theDate);
	//var myDate1 = myDate.format("isoDate");
	var myDate1 = myDate.format("dd-mm-yyyy");
	//console.log("myLogDate1 :: ", myDate1);
	return myDate1;
};
// ====================================================================== BO new Model implementation //////////////
// new ones edited from Example
var AccNewAssesmentVO = function(data, mode) {
	this.assessmentId = ko.observable();
	this.assessmentTitle = ko.observable('').extend({
		required : {
			message : 'Enter Assessment Title'
		}
	});

	this.assessmentType = ko.observable();

	this.assessmentType.assessmentTypeStr = ko.computed(function() {
		var str = "Default";
		if (ko.isObservable(this.assessmentType)) {
			//console.log("in if isObservable :: ")
			if (Number(this.assessmentType()) == 2) {
				str = 'Summative';

			} else {
				str = 'Formative';
			}
		} else {
			//console.log("in else isObservable :: ")
			if (Number(this.assessmentType) == 2) {
				str = 'Summative';

			} else {
				str = 'Formative';
			}
		}
		//console.log("in end :: " + str)
		return str;
	}, this);

	this.startDate = ko.observable().extend({
		required : {
			message : 'Enter Start Date.'
		}
	});
	this.endDate = ko.observable().extend({
		required : {
			message : 'Enter End Date.'
		}
	});

	this.startDateDisplay = ko.computed(function() {
		var sd = "";
		if (this.startDate()) {
			sd = getMyDate(this.startDate());
		}
		return sd;
	}, this);

	this.endDateDisplay = ko.computed(function() {
		var ed = "";
		if (this.endDate()) {
			ed = getMyDate(this.endDate());
		}
		return ed;
		//return this.startDate() + " - " + this.endDate();
	}, this);

	this.weightage = ko.observable('').extend({
		required : {
			message : 'Enter Weightage.'
		}
	});

	this.weightage.subscribe(function(value) {
		//console.log("this.weightage.subscribe :: ", value);
		if (tab3AssessmentViewModel.itemForEditing()) {
			//tab3AssessmentViewModel.totalWeightage(
			updateRemainingWaitage();
		}

	});

	this.reportlock = ko.observable();

	/**
	 * On Change of End Date AccNewAssesmentVO
	 */
	this.startDate.subscribe(function(value, ele) {
		console.log("AccNewAssesmentVO startDate value :: ", value);

		/*
		 var sdElement = jQuery('input[name="startDateDP"]')[0];
		 var edElement = jQuery('input[name="endDateDP"]')[0];

		 var dt1 = $(sdElement).datepicker('getDate');
		 var dt2 = $(edElement).datepicker('getDate');
		 if (tab3AssessmentViewModel.isOpen()) {
		 if (!byCode) {
		 self.checkForValidity("startDate");
		 }
		 }

		 //set min date of end date
		 $(edElement).datepicker("option", "minDate", dt1);

		 //Set the assessment dates accordingly

		 jQuery(".datepicker_ayp_start").datepicker("option", "minDate", dt1);
		 jQuery(".datepicker_ayp_end").datepicker("option", "minDate", dt1);

		 //set previous date here
		 self.startDate.previousDate = self.startDate();*/

	});

	this.cache = function() {
	};

	this.update(data, mode);

	this.errors = ko.validation.group(this, {
		deep : true
	});
};

//can pass fresh data to this function at anytime to apply updates or revert to a prior version
ko.utils.extend(AccNewAssesmentVO.prototype, {
	update : function(data, mode) {
		this.assessmentId(data.assessmentId || "");
		this.assessmentTitle(data.assessmentTitle || "");
		this.assessmentType(data.assessmentType || 1);

		this.startDate(data.startDate || '');
		this.endDate(data.endDate || '');
		this.weightage(data.weightage || '');
		this.reportlock(data.reportlock || 0);
		//save off the latest data for later use
		this.cache.latestData = data;

	},

	revert : function() {
		this.update(this.cache.latestData);
	}
});

var myMode = "addAssessment";
var mySaveMode = "";
var byCode = true;

var AccNewTermVO = function(data, mode) {
	var self = this;
	this.sectionId = ko.observable();
	this.termId = ko.observable();
	this.termTitle = ko.observable('').extend({
		required : {
			message : 'Enter term Title.'
		}
	});

	this.assessments = ko.observableArray();

	this.assessments.subscribe(function(value) {
		console.log("this.assessments.subscribe :: ", value);

		// var sdElement
		// var edElement
		// sdElement = jQuery('input[name="' + sdPreFix+index + '"]')[0];
		// edElement = jQuery('input[name="' + edPreFix+index + '"]')[0];

	});

	this.startDate = ko.observable('').extend({
		required : {
			message : 'Enter Start Date.'
		}
	});
	this.endDate = ko.observable('').extend({
		required : {
			message : 'Enter End Date.'
		}
	});

	self.checkForValidity = function(dateSourceType) {

		var message = "";
		ko.utils.arrayForEach(self.assessments(), function(item) {
			var itemEvent = item;

			if (ko.isObservable(itemEvent.startDate)) {
				//console.log("observable item", itemEvent)
				var strArr1 = itemEvent.startDate().split("-");
				var strArr2 = itemEvent.endDate().split("-");

			} else {
				//console.log("Non observable item", itemEvent)
				var strArr1 = itemEvent.startDate.split("-");
				var strArr2 = itemEvent.endDate.split("-");
			}
			var ayp_strArr1 = self.startDate().split("-");
			var ayp_strArr2 = self.endDate().split("-");
			// years, months, date
			var startDate = new Date(strArr1[0], Number(strArr1[1] - 1), strArr1[2]);
			var endDate = new Date(strArr2[0], Number(strArr2[1] - 1), strArr2[2]);

			var ayp_startDate = new Date(ayp_strArr1[0], Number(ayp_strArr1[1] - 1), ayp_strArr1[2]);
			var ayp_endDate = new Date(ayp_strArr2[0], Number(ayp_strArr2[1] - 1), ayp_strArr2[2]);

			//console.log("item Event:", self.startDate(), self.endDate(), startDate, endDate);
			//check for min max of date
			if (dateSourceType == "startDate") {
				if (ayp_startDate > startDate) {
					message = "there is a previous date exist in Assessments";
				}
			} else {
				if (ayp_endDate < endDate) {
					message = "there is a next date exist in Assessments";
				}
			}
		});

		//console.log("message :: ", message);
		if (message) {

			// Reset the date by dateSourceType
			if (dateSourceType == "startDate") {
				byCode = true;
				self.startDate(self.startDate.previousDate);
				byCode = false;
			}
			if (dateSourceType == "endDate") {
				byCode = true;
				self.endDate(self.endDate.previousDate);
				byCode = false;
			}
			tab3RootSelf.errorTitle("Date Range");
			tab3RootSelf.errorDesc(message);
			tab3RootSelf.openErrorDialog();

			message = "";
		}
	};
	/**
	 * On Change of End Date
	 */
	this.startDate.subscribe(function(value, ele) {
		//console.log("startDate value :: ", value);

		var sdElement = jQuery('input[name="startDateDP"]')[0];
		var edElement = jQuery('input[name="endDateDP"]')[0];

		var dt1 = $(sdElement).datepicker('getDate');
		var dt2 = $(edElement).datepicker('getDate');
		if (tab3AssessmentViewModel.isOpen()) {
			if (!byCode) {
				self.checkForValidity("startDate");
			}
		}

		//set min date of end date
		$(edElement).datepicker("option", "minDate", dt1);

		//Set the assessment dates accordingly
		jQuery(".datepicker_ayp_start").datepicker("option", "minDate", dt1);
		jQuery(".datepicker_ayp_end").datepicker("option", "minDate", dt1);

		//set previous date here
		self.startDate.previousDate = self.startDate();

	});

	this.endDate.subscribe(function(value) {
		//console.log("endDate value :: ", value);

		var sdElement = jQuery('input[name="startDateDP"]')[0];
		var edElement = jQuery('input[name="endDateDP"]')[0];

		var dt2 = $(edElement).datepicker('getDate');

		if (tab3AssessmentViewModel.isOpen()) {
			if (!byCode) {
				self.checkForValidity("endDate");
			}
		}

		//set max date of start date
		$(sdElement).datepicker("option", "maxDate", dt2);

		//Set the assessment dates accordingly
		jQuery(".datepicker_ayp_start").datepicker("option", "maxDate", dt2);
		jQuery(".datepicker_ayp_end").datepicker("option", "maxDate", dt2);

		//set previous date here
		self.endDate.previousDate = self.endDate();

	});

	this.startDate.totalDate = ko.computed(function() {
		var sd = "";
		var ed = "";
		if (this.startDate()) {
			sd = getMyDate(this.startDate());
		}
		if (this.endDate()) {
			ed = getMyDate(this.endDate());
		}

		return sd + " - " + ed;
		//return this.startDate() + " - " + this.endDate();

	}, this);

	// if edit mode then do not create the new Assesment VOs
	if (mode == "editTerm") {

		// if in edit mode
		var mappedData = jQuery.map(data.assessments, function(item) {
			return item;
		});
		this.assessments = ko.observableArray(mappedData);

	} else {
		if (data.termId == undefined) {

		} else {
			var mappedData = jQuery.map(data.assessments, function(item) {
				return new AccNewAssesmentVO(item);
			});

			this.assessments = ko.observableArray(mappedData);
		}

	};

	self.addAssessment = function(mode) {
		var assessItemToAdd;
		//new add set the item to be added for assessment
		assessItemToAdd = new AccNewAssesmentVO({
			"assessmentId" : "",
			"assessmentTitle" : "",
			"assessmentType" : 1,
			"startDate" : "",
			"endDate" : "",
			"weightage" : "",
			"reportlock" : 0
		});

		//console.log("")
		if (mode != "addTerm") {
			var isValid = self.doValidation();
			if (isValid) {
				self.assessments.push(assessItemToAdd);
				tab3RootSelf.changeMinMax();
			}
		} else {
			self.assessments.push(assessItemToAdd);
			tab3RootSelf.changeMinMax();
		}
	};
	//
	self.doValidation = function() {
		var returnVal = true;
		if (!self.startDate() || !self.endDate()) {
			tab3RootSelf.errorTitle("Term Duration");
			tab3RootSelf.errorDesc("please enter Term Duration");
			tab3RootSelf.openErrorDialog();

			returnVal = false;
			return returnVal;
		} else {
			ko.utils.arrayForEach(self.assessments(), function(item) {
				//editedItem.assessments()[0].errors
				var assessmentItem = item;
				//console.log("item :: ", item)
				//console.log("assessmentItem.errors.length :: ", assessmentItem.errors.length)
				/**
				 *TODO: Check it for only num > 0
				 */
				if (assessmentItem.weightage() == 0) {

					tab3RootSelf.errorTitle("Weightage");

					tab3RootSelf.errorDesc("Weightage Should be more than 0");
					tab3RootSelf.openErrorDialog();
					returnVal = false;
					return returnVal;
				}
				if (assessmentItem.errors().length > 0) {
					tab3RootSelf.errorTitle("All Fields for Assessment");
					tab3RootSelf.errorDesc("please enter All Fields for Assessment");
					tab3RootSelf.openErrorDialog();

					returnVal = false;
					return returnVal;
				}
			});
		}
		return returnVal;
	};

	if (mode == "addTerm") {
		self.addAssessment(mode);
	}

	self.cache = function() {
	};

	//populate our model with the initial data
	self.update(data, mode);
	self.errors = ko.validation.group(self, {
		deep : true
	});
};

ko.utils.extend(AccNewTermVO.prototype, {
	update : function(data, mode) {
		//console.log("data.startDate :: " , data.startDate)
		if (mode == "editTerm") {
			this.sectionId(data.sectionId);
		} else {
			this.sectionId(data.sectionId || sectionId);
		}

		this.termId(data.termId || "");
		this.termTitle(data.termTitle || "");
		this.startDate(data.startDate || '');
		this.endDate(data.endDate || '');
		if (mode == "editTerm") {
			if (data.assessments) {
				var tempMappedData = jQuery.map(data.assessments, function(item) {
					return new AccNewAssesmentVO(item, mode);
				});
				this.assessments(tempMappedData);
			}
		} else if (mode == "save") {
			//also update the assessments array as it is in editmode
			this.assessments(data.assessments);
		} else {
			// for new it will be undefined.
			if (data.assessments) {
				var tempMappedData = jQuery.map(data.assessments, function(item) {
					return new AccNewAssesmentVO(item);
				});
				this.assessments(tempMappedData);
			}

		}

		//save off the latest data for later use
		this.cache.latestData = data;
	},

	revert : function() {
		this.update(this.cache.latestData, "");
	}
});

var myNewFrameworkViewModel = function() {

	var self = this;
	tab3RootSelf = self;

	self.termVOarr = ko.observableArray([]);
	//New Url by Narshima
	self.url = baseOperationUrl + "getSecPlanTerms&sectionId=" + sectionId;
	//self.url = "../json/tab3.json"

	self.init = function() {
		displayAttendance = false;
		loadTermsList();
		console.log("called init");
	};
	function loadTermsList() {
		showLoader(true, TYPE_LOADING);
		var jqxhr = $.getJSON(self.url, {

			returnformat : 'json'
		}, function(allData) {
			console.log("allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				//return new newTermVO(item.sectionId, item.termTitle, item.startDate, item.endDate, item.assessments)
				return new AccNewTermVO(item);

			});
			self.termVOarr(mappedData);
		});

		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			console.log("second success", allData[0]);
		});
		jqxhr.fail(function() {
			console.log("error myNewFrameworkViewModel tab3");
		});
		jqxhr.always(function() {
			console.log("complete");
		});
		jqxhr.complete(function() {
			console.log("second complete");
			self.assignVars();
		});
		/** ----------------------------------------- End Event Listeners */
	}


	self.assignVars = function(item) {
		showLoader(false);
		byCode = false;

		// $(".datepicker").datepicker( 'option' , 'beforeShowDay', highlightDays);
		// $(".datepicker_ayp_start").datepicker( 'option' , 'beforeShowDay', highlightDays);
		// $(".datepicker_ayp_end").datepicker( 'option' , 'beforeShowDay', highlightDays);
		//

		var sdElement = jQuery('input[name="startDateDP"]')[0];
		var edElement = jQuery('input[name="endDateDP"]')[0];

		var dt1 = $(sdElement).datepicker('getDate');
		var dt2 = $(edElement).datepicker('getDate');

		$(edElement).datepicker("option", "minDate", dt1);
		$(sdElement).datepicker("option", "maxDate", dt2);

	};
	self.deleteClick = function(item) {
		$("#dialog-confirmAssessmentDelete").dialog("open");
		$("#dialog-confirmAssessmentDelete #delete").click(function() {
			$("#dialog-confirmAssessmentDelete").dialog("close");
			self.termVOarr.remove(item);
			deleteAssessmentWindowsServerTerm(item.termId());
		});
		$("#dialog-confirmAssessmentDelete #cencel").click(function() {
			$("#dialog-confirmAssessmentDelete").dialog("close");
		});
	};

	this.deleteAssessment = this.deleteAssessment.bind(this);
	//
	// self.deleteAssessment = function(item) {
	//
	// }

	self.getMyTotalWeightage = function(editedItem) {
		/**
		 *Check for Weightage sum to 100.
		 */
		var myTotalWeightage = 0;
		var editTermId = "";

		if (editedItem) {
			editTermId = editedItem.termId();
		}
		var myEditWeightage = 0;
		if (editedItem) {

			for (var c = 0; c < editedItem.assessments().length; c++) {
				var assessmentItem = editedItem.assessments()[c];

				if (ko.isObservable(assessmentItem.weightage)) {
					myEditWeightage += Number(assessmentItem.weightage());
				} else {
					myEditWeightage += Number(assessmentItem.weightage);
				}
			};

			mySaveMode = "";

		};

		var myNonEditWeightage = 0;
		for (var i = 0; i < this.termVOarr().length; i++) {

			var termItem = this.termVOarr()[i];
			/**
			 *If the editing item then take form edited value.
			 */
			if (termItem.termId() == editTermId && editedItem) {

			} else {
				for (var j = 0; j < termItem.assessments().length; j++) {
					var assessmentItem = termItem.assessments()[j];

					if (ko.isObservable(assessmentItem.weightage)) {
						myNonEditWeightage += Number(assessmentItem.weightage());
					} else {
						myNonEditWeightage += Number(assessmentItem.weightage);
					}
				};
			}
		};
		myTotalWeightage = myNonEditWeightage + myEditWeightage;
		//console.log("getMyTotalWeightage myEditWeightage :: ", myEditWeightage);
		//console.log("getMyTotalWeightage myNonEditWeightage :: ", myNonEditWeightage);
		//console.log("getMyTotalWeightage myTotalWeightage :: ", myTotalWeightage);

		return myTotalWeightage;
	};

	self.getTotalWeightage = function(editedItem) {
		/**
		 *Check for Weightage sum to 100.
		 */
		var myTotalWeightage = 0;
		var editTermId = "";

		if (editedItem) {
			editTermId = editedItem.termId();
		}
		var myEditWeightage = 0;
		if (mySaveMode == "NewTermSave" && editedItem) {

			for (var c = 0; c < editedItem.assessments().length; c++) {
				var assessmentItem = editedItem.assessments()[c];

				if (ko.isObservable(assessmentItem.weightage)) {
					myEditWeightage += Number(assessmentItem.weightage());
				} else {
					myEditWeightage += Number(assessmentItem.weightage);
				}
			};

			mySaveMode = "";

		};

		var myNonEditWeightage = 0;
		for (var i = 0; i < this.termVOarr().length; i++) {

			var termItem = this.termVOarr()[i];
			/**
			 *If the editing item then take form edited value.
			 */
			if (termItem.termId() == editTermId && editedItem) {

			} else {
				for (var j = 0; j < termItem.assessments().length; j++) {
					var assessmentItem = termItem.assessments()[j];

					if (ko.isObservable(assessmentItem.weightage)) {
						myNonEditWeightage += Number(assessmentItem.weightage());
					} else {
						myNonEditWeightage += Number(assessmentItem.weightage);
					}
				};
			}
		};
		myTotalWeightage = myNonEditWeightage + myEditWeightage;
		//console.log("myEditWeightage :: ", myEditWeightage);
		//console.log("myNonEditWeightage :: ", myNonEditWeightage);
		//console.log("myTotalWeightage :: ", myTotalWeightage);

		return myTotalWeightage;
	};

	this.totalWeightage = ko.observable();
	this.totalWeightage.remainingWeightage = ko.observable();

	this.newTotalWeightage = ko.computed({
		read : function(editItem) {
			this.totalWeightage(self.getTotalWeightage(editItem));
			return self.getTotalWeightage(editItem);
		},
		write : function(value) {
			this.totalWeightage(isNaN(value) ? 0 : value);
			// Write to underlying storage
		},
		owner : this
	});

	this.itemToAdd = ko.observable();
	this.itemParentToAdd = ko.observable();

	this.assessItemToAdd = ko.observable();
	this.assessItemParentToAdd = ko.observable();

	//hold the currently selected item
	this.selectedItem = ko.observable();

	//make edits to a copy
	this.itemForEditing = ko.observable();

	this.itemForEditing.subscribe(function(value) {
		console.log("this.itemForEditing.subscribe :: ", value);
	});

	this.selectItem = this.selectItem.bind(this);
	this.acceptItem = this.acceptItem.bind(this);
	this.revertItem = this.revertItem.bind(this);
	/////////////////////////////////

	self.isErrorDialogOpen = ko.observable(false);
	self.openErrorDialog = function() {
		this.isErrorDialogOpen(true);
	};
	self.closeErrorDialog = function() {
		this.isErrorDialogOpen(false);
	};
	/////////////////////////////////

	self.isOpen = ko.observable(false);
	self.open = function() {
		this.isOpen(true);
	};
	self.close = function() {
		this.isOpen(false);
		self.myCurrentMode("");
	};

	this.isOpen.subscribe(function(value) {
		console.log("this.isOpen.subscribe :: ", value);
		if (value) {
			/**
			 *Set the date ranges
			 */
			tab3RootSelf.changeMinMax();
			updateRemainingWaitage();
		}
	});

	self.errorTitle = ko.observable("Some Error Title!!!");
	self.errorDesc = ko.observable("Some Error !!!");
	self.mytitle = ko.observable("Define Term");
	self.myCurrentMode = ko.observable("");
	//Edit Term
	/////////////////////////////////////////
	self.lastSavedJson = ko.observable("");
	self.onSaved = function(edited) {
		//var saveDataStr = JSON.stringify(ko.toJS(edited), null, 2);

		var mapping = {
			'ignore' : ["errors", "startDateDisplay", "endDateDisplay"]
		};

		var jsonData = ko.mapping.toJSON(edited, mapping);

		console.log("jsonData \n", jsonData);
		//console.log("jsonData \n",jsonData);
		saveAssessmentWindowsServerTerm(jsonData);

		/**
		 *Done: call updateAllDates
		 *
		 * from datecontroller.js
		 */

		updateAllDates();

		self.lastSavedJson(jsonData);
	};
	self.errors = ko.validation.group(self, {
		deep : true
	});
	self.changeMinMax = function() {

		var sdElement = jQuery('input[name="startDateDP"]')[0];
		var edElement = jQuery('input[name="endDateDP"]')[0];

		var dt1 = $(sdElement).datepicker('getDate');
		var dt2 = $(edElement).datepicker('getDate');

		jQuery(".datepicker_ayp_start").datepicker("option", "minDate", dt1);
		jQuery(".datepicker_ayp_end").datepicker("option", "minDate", dt1);
		jQuery(".datepicker_ayp_start").datepicker("option", "maxDate", dt2);
		jQuery(".datepicker_ayp_end").datepicker("option", "maxDate", dt2);
	};

	self.onFocusIn = function(element) {
		console.log("onFocusIn :: ");
		return;
		var aypStartDate = getMyDateFromStr(self.selectedItem().startDate());
		var aypEndDate = getMyDateFromStr(self.selectedItem().endDate());

		var index = element.name.substr(3);
		var prefix = element.name.substr(0, 3);
		var sdPreFix = "sd_";
		var edPreFix = "ed_";

		var dt1;
		var dt2;
		var isAssessmentDatePicker = false;
		//
		if (prefix == sdPreFix) {
			//on start date Selected
			isAssessmentDatePicker = true;

			if (index == 0) {
				//the first startdate of assessment
				dt1 = aypStartDate;
				dt2 = aypEndDate;
			} else {
				var preindex = index - 1;
				var myPreElement = jQuery('input[name="' + edPreFix + preindex + '"]')[0];
				dt1 = $(myPreElement).datepicker('getDate');
				dt2 = aypEndDate;
			}
			console.log("edElement ::if ");
		} else if (prefix == edPreFix) {
			//on end date Selected
			isAssessmentDatePicker = true;
			var myPreElement = jQuery('input[name="' + sdPreFix + index + '"]')[0];
			dt1 = $(myPreElement).datepicker('getDate');
			dt2 = aypEndDate;
		}

		//set the min max date to ccurrent element.
		if (isAssessmentDatePicker) {
			$(element).datepicker("option", "minDate", dt1);
			$(element).datepicker("option", "maxDate", dt2);
		}
	};

	self.onDateChangex = function(element) {

		console.log("on dateChangex name  >>> ", element.name);

	};
	self.onDateChange = function(element) {
		//tab3AssessmentViewModel.onDateChange(element)
		console.log("on dateChange name  >>> ", element.name);
		//return;
		var sdElement;
		var edElement;
		var index = element.name.substr(3);
		var prefix = element.name.substr(0, 3);
		var sdPreFix = "sd_";
		var edPreFix = "ed_";
		//
		console.log("prefix :: ", prefix);
		if (prefix == edPreFix) {
			//on end date Selected
			edElement = element;
			sdElement = jQuery('input[name="' + sdPreFix+index + '"]')[0];

			var dt1 = $(sdElement).datepicker('getDate');
			var dt2 = $(edElement).datepicker('getDate');

			//console.log(dt1);
			//console.log(dt2);
			//$(sdElement).datepicker("option", "minDate", "22-03-2013");
			$(sdElement).datepicker("option", "maxDate", dt2);
			console.log("edElement ::if ", sdElement);

			console.log("edElement ::if ");

		} else if (prefix == sdPreFix) {
			//on start date Selected
			edElement = jQuery('input[name="' + edPreFix+index + '"]')[0];
			sdElement = element;

			var dt1 = $(sdElement).datepicker('getDate');
			var dt2 = $(edElement).datepicker('getDate');

			sdElement = element;
			edElement = jQuery('input[name="' + edPreFix+index + '"]')[0];
			$(edElement).datepicker("option", "minDate", dt1);

			console.log("sdElement ::else ", sdElement);
			console.log("edElement ::else ");

		}
		;

		//$('#dt2').datepicker('option', 'minDate', date2);

	};
};

ko.utils.extend(myNewFrameworkViewModel.prototype, {
	//Prasanna
	addTermItem : function(item) {
		this.mytitle("Define Term");
		myMode = "addTerm";
		this.myCurrentMode(myMode);

		this.itemParentToAdd = this.termVOarr;
		//set the item to be added for term
		this.itemToAdd = new AccNewTermVO(ko.toJS(item), myMode);
		this.selectedItem(this.itemToAdd);
		this.itemForEditing(this.itemToAdd);
		this.open();
	},

	//select an item and make a copy of it for editing
	selectItem : function(item) {
		this.mytitle("Edit Term");

		myMode = "editTerm";
		this.myCurrentMode(myMode);
		this.selectedItem(item);
		this.itemForEditing(new AccNewTermVO(ko.toJS(item)), myMode);
		updateRemainingWaitage();
		//Prasanna
		this.open();
	},

	acceptItem : function(item) {
		//Prasanna
		var editedItem = this.itemForEditing();

		var selected = this.selectedItem(), edited = ko.toJS(this.itemForEditing());

		/**
		 * BO Validation
		 * http://hemant-vikram.blogspot.in/2012/09/knockout-model-and-validating-inner.html
		 */

		mySaveMode = "NewTermSave";

		// BO Dates Overlap Check
		/**
		 *A Compare Function
		 */
		function compare(a, b) {
			if (a.startDate < b.startDate)
				return -1;
			if (a.startDate > b.startDate)
				return 1;
			return 0;
		}

		/**
		 *Return the date as a Number Year Month Date
		 */

		function myDateAsNum(dateObj) {
			var num = dateObj.toString();
			num = Number(num.split("-").join(""));
			return num;
		}

		/**
		 *Return the date Array
		 */

		function createDateNumbersArray(assessments, localAssessmentType) {
			var dateArr = new Array();
			for (var i = 0; i < assessments.length; i++) {
				var assObj = assessments[i];
				var dateObj = new Object();
				//Check for Formative or Summative
				if (assObj.assessmentType() == localAssessmentType) {
					dateObj.startDate = myDateAsNum(assObj.startDate());
					dateObj.endDate = myDateAsNum(assObj.endDate());
					if (dateObj.endDate < dateObj.startDate) {
						return null;
					}
					dateObj.ctr = i;
					dateArr.push(dateObj);
				}

			};
			return dateArr;
		}

		function checkOverlap(myDateArray) {
			for (var i = 1; i < myDateArray.length; i++) {
				var preDateObj = myDateArray[i - 1];
				var curDateObj = myDateArray[i];
				/**
				 *Check if the last one is greater
				 * then break as it is Overlapping.
				 */
				if (preDateObj.endDate > curDateObj.startDate) {
					return true;
				}
			}
			return false;
		}

		for (var i = 1; i < 3; i++) {
			var myDateArray = createDateNumbersArray(editedItem.assessments(), i);
			if (myDateArray) {
				var newArr = new Array(myDateArray);
				console.log("newArr :: ", newArr);

				myDateArray.sort(compare);
				console.log("myDateArray :: ", myDateArray);
				var isOverLapping = checkOverlap(myDateArray);
				console.log("isOverLapping :: ", isOverLapping);

				/**
				 *TODO: 29Aug
				 * Check for Summative and Formative differently.
				 */
				if (isOverLapping) {
					tab3RootSelf.errorTitle("Assessment Dates Overlap");
					tab3RootSelf.errorDesc("Assessment Dates Overlapping");
					tab3RootSelf.openErrorDialog();
					return;
				}

			} else {
				/**
				 *It has Come Null so return from here;
				 */

				tab3RootSelf.errorTitle("Assessment Dates");
				tab3RootSelf.errorDesc("Assessment Start Date is Later than End Date");
				tab3RootSelf.openErrorDialog();
				return;
			}
		};

		// EO Dates Overlap Check
		var errorExists = false;

		/**
		 *Here also Check for Validation
		 */
		var isValid = editedItem.doValidation();
		if (!isValid) {
			return;
		}

		/**
		 *Check for Weightage sum to 100.
		 */
		var myTotalWeightage = this.getTotalWeightage(editedItem);
		//this.totalWeightage(myTotalWeightage);

		console.log("myTotalWeightage :: ", myTotalWeightage);

		/**
		 *TODO: 29Aug All Terms totalWeightage less =100
		 */
		if (myTotalWeightage > 100) {
			tab3RootSelf.errorTitle("Total Weightage");
			tab3RootSelf.errorDesc("Total Weightage Should not be more than 100");
			tab3RootSelf.openErrorDialog();

			return;
		}

		ko.utils.arrayForEach(editedItem.assessments(), function(item) {
			//editedItem.assessments()[0].errors
			var assessmentItem = item;
			console.log("item :: ", item);
			console.log("assessmentItem.errors.length :: ", assessmentItem.errors.length);
			if (assessmentItem.errors().length > 0) {
				assessmentItem.errors.showAllMessages(true);
				errorExists = true;
			}
		});

		if (editedItem.errors().length != 0) {//verifying the errors attribute using the count of errors
			editedItem.errors.showAllMessages(true);
			//displaying the corresponding error messages
			errorExists = true;
			//set error flag to stop further processing
		}
		console.log("itemerrorExists:: ", errorExists);

		if (errorExists) {
			tab3RootSelf.errorTitle("Fill all Fields");
			tab3RootSelf.errorDesc("Please Fill the Remaining Fields");
			tab3RootSelf.openErrorDialog();
			return;
			//returning the control providing user a chance to correct the issues
		} else {
			this.close();
			/**
			 *Store the total Weightage in Model
			 */
			this.newTotalWeightage(myTotalWeightage);

			//clean copy of edited
			//apply updates from the edited item to the selected item
			selected.update(edited, "save");
			//clear selected item
			this.selectedItem(null);
			this.itemForEditing(null);
		}
		/**
		 * EO Validation
		 */

		//add the term to array
		if (myMode == "addTerm") {
			this.itemParentToAdd.push(this.itemToAdd);
		}
		this.onSaved(edited);
	},

	//just throw away the edited item and clear the selected observables
	deleteAssessment : function(item) {

		console.log("item 22 :: ", item);
		console.log("tthis.itemForEditing().assessments():: ", this.itemForEditing().assessments());
		//console.log("this.itemForEditing.assessments() :: ", this.itemForEditing.assessments());
		this.itemForEditing().assessments.remove(item);

		updateRemainingWaitage()

	},
	revertItem : function() {
		//Prasanna
		this.close();
		this.selectedItem(null);
		this.itemForEditing(null);
	}
});
// ====================================================================== EO new Model implementation //////////////
/**
 * EO Tab3 ViewModel
 */
// function jsonIOError(msg) {
// console.log("jsonIOError" , msg);
// }

function updateRemainingWaitage() {
	tab3AssessmentViewModel.totalWeightage.remainingWeightage(100 - tab3AssessmentViewModel.getMyTotalWeightage(tab3AssessmentViewModel.itemForEditing()));
}

function saveAssessmentWindowsServerTerm(saveDataStr) {
	var AssessmentWindowsServer_SAVE = baseOperationUrl + "saveSecPlanTerms";

	showLoader(true, TYPE_SAVING);
	var localData = {
		savedata : saveDataStr
	};
	$.ajax({
		url : AssessmentWindowsServer_SAVE,
		type : 'POST',
		data : localData,
		dataType : 'json',
		async : false,
		success : function(msg) {
			console.log("saveAssessmentWindowsServerTerm Operation copmpleted", msg);
			showLoader(false);
			tab3AssessmentViewModel.init();
		},
		error : jsonIOError
	});
};

function deleteAssessmentWindowsServerTerm(locTermID) {
	var AssessmentWindowsServer_DeleteTerm = baseOperationUrl + "deleteSecPlanTerms";
	showLoader(true, TYPE_DELETING);
	var localData = {
		termId : locTermID
	};
	$.ajax({
		url : AssessmentWindowsServer_DeleteTerm,
		type : 'POST',
		data : localData,
		dataType : 'json',
		async : false,
		success : function(msg) {
			console.log("--- deleteAssessmentWindowsServerTerm Operation copmpleted", msg);
			showLoader(false);
		},
		error : jsonIOError
	});
}